<template>
  <div>
    <el-dialog :title="title" :visible="visible" @close="handleClose" width="800px">
      <el-form :model="form" label-position="right" :rules="rules" ref="formRef">
        <el-row :gutter="10">
          <el-col :span="12">
            <el-form-item label="货架号/货架数" :label-width="formLabelWidth" prop="flag">
              <el-switch v-model="form.flag" active-text="货架号" inactive-text="货架数" :active-value="'1'"
                :inactive-value="'0'">
              </el-switch>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="货位类型" :label-width="formLabelWidth" prop="type">
              <el-select clearable v-model="form.type" style="width: 100%;" placeholder="请选择货位类型">
                <el-option v-for="(item, index) in typeList" :key="index" :value="item.value" :label="item.label">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12" v-if="form.flag == '1'">
            <el-form-item label="货架号" :label-width="formLabelWidth" prop="hjNum">
              <el-input v-model="form.hjNum" placeholder="请输入货位数量" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="货位数量" :label-width="formLabelWidth" prop="positionsPerLayer">
              <el-input v-model="form.positionsPerLayer" placeholder="请输入货位数量" />
            </el-form-item>
          </el-col>
         <el-col :span="12" v-if="form.flag == '0'">
            <el-form-item label="货架数量" :label-width="formLabelWidth" prop="def2">
              <el-input v-model="form.def2" placeholder="非地堆只能输入整数" @input="filterDef2Input" />
            </el-form-item>
          </el-col>
<!--          <el-col :span="12">
            <span style="color: red;">*地堆货架数量可以是整数或者字母，非地堆只能是整数</span>
          </el-col> -->
        </el-row>
      </el-form>
      <locationPrint v-show="false" ref="locationPrintRef"></locationPrint>
      <div slot="footer" class="dialog-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button type="primary" @click="submit">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import {
    locationEditOperation,
    locationAddOperation,
    basicStoShelf
  } from "@/api/index/warehouse";
  import locationPrint from '@/views/basic/print/locationPrint.vue'
  export default {
    data() {
      const validateDef2 = (rule, value, callback) => {
        if (!value) {
          return callback(new Error('货架数量不能为空'));
        }
        if (this.isGroundStack) {
          if (!/^[a-zA-Z0-9]+$/.test(value)) {
            callback(new Error('只能输入字母和数字，不能输入中文'));
          } else {
            callback();
          }
        } else {
          if (!/^\d+$/.test(value)) {
            callback(new Error('只能输入整数'));
          } else {
            callback();
          }
        }
      };
      return {
        form: {
          positionsPerLayer: '',
          layerCount: '',
          def1: '',
          def2: '',
          sonCode: "",
          enableState: '0',
          isSonShow: 0,
          hwbh:'',
          flag:'0',
          hjNum:''
        },
        typeList:[
          {
            value:0,
            label:'零货'
          },{
            value:1,
            label:'整货'
          }
        ],//货位类型
        title: '',
        formLabelWidth: '100px',
        areaList: [],
        rules: {
          def1: [{
            required: true,
            message: '货位类型不能为空',
            trigger: 'change',
          }],
          def2: [{
            required: true,
            message: '货架数量不能为空',
          }, {
            validator: validateDef2,
            trigger: 'blur'
          }],
          positionsPerLayer: [{
            required: true,
            message: '层货位数',
            trigger: 'blur'
          }],
          layerCount: [{
            required: true,
            message: '货架层数不能为空',
            trigger: 'blur'
          }],
          type: [{
            required: true,
            message: '货位类型不能为空',
            trigger: 'blur'
          }]
        }
      }
    },
    components: {
      locationPrint
    },
    props: {
      visible: { // 接收父组件通过sync传递的visible属性
        type: Boolean,
        default: false
      },
    },
    watch: {
      'form.def1'(newVal, oldVal) {
        // 当货位类型变化时，清空货架数量
        this.form.def2 = '';
        this.form.layerCount = '';
        this.form.positionsPerLayer = '';
      }
    },
    computed: {
      isGroundStack() {
        const selectedType = this.areaList.find(item => item.tag === this.form.def1);
        return selectedType && selectedType.name === '地堆'; // 根据实际label名称调整
      }
    },
    created() {
      //获取货位编码
      this.getArea();
    },
    methods: {
      // 添加输入过滤方法
      filterDef2Input() {
        if (this.isGroundStack) {
          // 地堆类型：过滤掉中文和非字母数字字符
          this.form.def2 = this.form.def2.replace(/[^a-zA-Z0-9]/g, '');
        } else {
          // 非地堆类型：只允许数字
          this.form.def2 = this.form.def2.replace(/[^\d]/g, '');
        }
      },
      //获取货位编码
      getArea() {
        basicStoShelf().then(res => {
          this.areaList = res.rows;
        })
      },
      openDialog(val,data1,data2) {
          this.title = '新增货位';
          this.form = {
            layerCount: '',
            positionsPerLayer: '',
            enableState: '0',
            def2: '',
            def1: '',
            sonCode: '',
            isSonShow: 0,
            hwbh:data1,
            flag:'0',
            hjNum:'',
            stoAreaId: Array.isArray(data2) ? data2.join(',') : data2,
          }
      },
      // 提取重置表单的逻辑
      handleClose() {
        // 通过事件通知父组件更新visible值，触发update:visible事件
        this.$emit('update:visible', false);
        this.$nextTick(() => {
          this.$refs.formRef.resetFields();
        })
      },
      //提交表单
      submit() {
        this.$refs.formRef.validate((valid) => {
          if (valid) {
            const apiMethod = this.title === '新增货位' ? locationAddOperation : locationEditOperation;
            // 调用相应的 API 方法
            apiMethod(this.form).then(res => {
              if (res.code == 200) {
                this.$emit('addSuccess'); // 通知父组件添加成功
                this.$message({
                  message: res.msg, // 显示成功消息
                  type: 'success',
                });
                // 提交成功后可以选择清空表单
                this.handleClose();
              }
            })
          } else {
            // 校验失败
            return false;
          }
        });
      }
    }
  }
</script>

<style></style>
